import React, { memo, useEffect, useState, forwardRef, useContext } from 'react';
import { connect } from 'umi';
import { history } from 'umi'
import { Spin, Form, Button, Checkbox, Col, Row, Select, message } from 'antd';
import isEmpty from 'lodash/isEmpty';
import mathCeil from 'lodash/ceil';
import mathFloor from 'lodash/floor';
import classNames from 'classnames';

import { withRoutePage } from '@/utils/enhanceUtils';
import AuthComponent from '@/utils/auth/AuthComponent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';

// import { formatMessage } from 'umi';
import {
    queryWorkingInfo,
    queryWorkingCalculate,
    queryDictList,
    onSaveWorkingTimeSetting,
    queryBaseSettingInfo,
    querySalaryYearList
} from '@/services/salaryManage/salaryCalculate';

import { TabMenuRouter, TabContextMenuFilter } from '@/pages/SalaryManage/components/MenuFilterRouter';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';

import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import { MONTHList } from '@/pages/SalaryManage/utils/staticList';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '../style.less';

const { Option } = Select;

/** 【工时设置】权限码 */
const SALARY_WORKHOUR_AUTH_CODE = 'finance:setting:salary:workhour';

const MENU_AUTH_CODE_MAP = {
    CN: [SALARY_WORKHOUR_AUTH_CODE],
    SG: [SALARY_WORKHOUR_AUTH_CODE]
};

const formItemLayout = {
    labelCol: {
        md: { span: 9 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 15 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

const workTimeInfoLayout = {
    wrapperCol: {
        md: { span: 24 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

// 下拉搜索插件
const CustomerSelect = memo(
    forwardRef(({ value, onChange, dataList = [], disabled, ...otherProps }) => (
        <Select value={value} onChange={onChange} disabled={disabled} {...otherProps}>
            {dataList.map(item => (
                <Option value={item.key} key={item.key}>
                    {item.value}
                </Option>
            ))}
        </Select>
    ))
);

// 通用工作日设置组件
const CommonWorkSetting = memo(
    forwardRef(
        ({
            form,
            editData,
            currentMoney,
            paramKeys = {},
            workRuleList,
            baseSettingInfo = {},
            disabled,
            required = false
        }) => {
            const { getFieldDecorator, getFieldValue } = form;
            const getMoney = (index, type) => {
                const dataList = getFieldValue(paramKeys.workListWrapKey);
                const currentData = dataList[index] || {};
                if (currentData.workDays && currentData.dayHours) {
                    const hoursMoney = currentMoney / currentData.workDays / currentData.dayHours;
                    switch (baseSettingInfo.roundingMode) {
                        case '2':
                            return type === 'hours'
                                ? mathFloor(hoursMoney, baseSettingInfo.scale || 2)
                                : mathFloor(hoursMoney / 60, baseSettingInfo.scale || 2);
                        case '3':
                            return type === 'hours'
                                ? mathCeil(hoursMoney, baseSettingInfo.scale || 2)
                                : mathCeil(hoursMoney / 60, baseSettingInfo.scale || 2);
                        default:
                            return type === 'hours'
                                ? hoursMoney.toFixed(baseSettingInfo.scale || 2)
                                : (hoursMoney / 60).toFixed(baseSettingInfo.scale || 2);
                    }
                }
                return 0;
            };
            return (
                <div className={styles.workTimeWrap}>
                    <div className={styles.workingCheckboxWrap}>
                        {getFieldDecorator(paramKeys.enableKey, {
                            initialValue: !!editData[paramKeys.enableKey],
                            valuePropName: 'checked'
                        })(<Checkbox disabled={required}>{paramKeys.columnName}</Checkbox>)}
                    </div>

                    {(editData.monthList || []).map((item, index) => (
                        // eslint-disable-next-line react/no-array-index-key
                        <Row gutter={24} key={`${item.workYear}-${item.workMonth}-${item.workDays}-${index}`}>
                            <Col span={15}>
                                <div className={styles.workTimeFormWrap}>
                                    <Col span={8}>
                                        <Form.Item label={item.name || '每月'}>
                                            <div className={styles.workTimeItemWrap}>
                                                {getFieldDecorator(`${paramKeys.workListWrapKey}.${index}.workDays`, {
                                                    initialValue: item.workDays,
                                                    rules: [
                                                        {
                                                            required: getFieldValue(paramKeys.enableKey),
                                                            message: '请输入天数'
                                                        },
                                                        {
                                                            type: 'number',
                                                            min: 0,
                                                            message: '天数不能小于0'
                                                        },
                                                        {
                                                            type: 'number',
                                                            max: 31,
                                                            message: '天数不能大于31'
                                                        }
                                                    ]
                                                })(
                                                    <NumberSettingInput
                                                        min={0}
                                                        style={{ minWidth: '100px', width: '65%' }}
                                                        disabled={
                                                            !getFieldValue(paramKeys.enableKey) ||
                                                            disabled ||
                                                            !item.isEdit
                                                        }
                                                        thousandsSeparator=","
                                                        maxLength={15}
                                                    />
                                                )}
                                                <span className={styles.workTimeItemUnit}>天</span>
                                            </div>
                                        </Form.Item>
                                    </Col>
                                    <Col span={8}>
                                        <Form.Item label="工作制">
                                            <div className={styles.workTimeItemWrap}>
                                                {getFieldDecorator(`${paramKeys.workListWrapKey}.${index}.workRule`, {
                                                    initialValue: item.workRule,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择工作制'
                                                        }
                                                    ]
                                                })(
                                                    <CustomerSelect
                                                        disabled
                                                        dataList={workRuleList}
                                                        style={{
                                                            width: '65%',
                                                            minWidth: 100
                                                        }}
                                                    />
                                                )}
                                                <span className={styles.workTimeItemUnit}>每周</span>
                                            </div>
                                        </Form.Item>
                                    </Col>
                                    <Col span={8}>
                                        <Form.Item label="每天">
                                            <div className={styles.workTimeItemWrap}>
                                                {getFieldDecorator(`${paramKeys.workListWrapKey}.${index}.dayHours`, {
                                                    initialValue: item.dayHours,
                                                    rules: [
                                                        {
                                                            required: getFieldValue(paramKeys.enableKey),
                                                            message: '请输入小时'
                                                        },
                                                        {
                                                            type: 'number',
                                                            min: 0,
                                                            message: '小时数不能小于0'
                                                        },
                                                        {
                                                            type: 'number',
                                                            max: 24,
                                                            message: '小时数不能大于24'
                                                        }
                                                    ]
                                                })(
                                                    <NumberSettingInput
                                                        min={0}
                                                        style={{ minWidth: '100px', width: '60%' }}
                                                        disabled={!getFieldValue(paramKeys.enableKey) || !item.isEdit}
                                                        thousandsSeparator=","
                                                        maxLength={15}
                                                    />
                                                )}
                                                <span className={styles.workTimeItemUnit}>小时</span>
                                            </div>
                                        </Form.Item>
                                    </Col>
                                </div>
                            </Col>
                            <Col span={9}>
                                <div className={styles.workTimeInfoWrap}>
                                    <Form.Item {...workTimeInfoLayout}>
                                        <div className={styles.workTimeInfoContent}>
                                            <span className={styles.workTimeInfoTextNormal}>
                                                {getMoney(index, 'hours')}
                                            </span>
                                            <span className={styles.workTimeInfoTextGray}>元/小时</span>
                                            <span className={styles.workTimeInfoLine} />
                                            <span className={styles.workTimeInfoTextNormal}>
                                                {getMoney(index, 'minute')}
                                            </span>
                                            <span className={styles.workTimeInfoTextGray}>元/分钟</span>
                                        </div>
                                    </Form.Item>
                                </div>
                            </Col>
                        </Row>
                    ))}
                </div>
            );
        }
    )
);

const WorkingTimeSetting = ({ form }) => {
    const [pageLoading, setPageLoading] = useState(false);
    const { validateFieldsAndScroll, resetFields } = form;
    const [commonData, setCommonData] = useState({});
    const [resignData, setResignData] = useState({});
    const [generalData, setGeneralData] = useState({});
    const [baseSettingInfo, setBaseSettingInfo] = useState({});
    const [workRuleList, setWorkRuleList] = useState([]);
    const [yearList, setYearList] = useState([]);
    const [currentMoney, setCurrentMoney] = useState(10000);
    const [organizationTreeData, setOrganizationTreeData] = useState([]);
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);

    const {
        store: { selectOrganizationCode: selOrgCode },
        mergeTabStore
    } = useContext(TabStoreContext);

    useEffect(() => {
        if (selOrgCode && selOrgCode !== selectOrganizationCode) {
            setSelectOrganizationCode(selOrgCode);
        }
    }, [selOrgCode]);

    const { getFieldDecorator, getFieldsValue, setFieldsValue } = form;
    const commonDataIsEmpty = isEmpty(commonData);
    const onSave = () => {
        try {
            validateFieldsAndScroll(async (err, values) => {
                if (!err) {
                    if (!values.commonEnable && !values.resignEnable) {
                        message.error('保存失败，请至少选择一项设置');
                        return;
                    }
                    setPageLoading(true);
                    const params = {
                        commonEnable: values.commonEnable,
                        organizationCode: selectOrganizationCode,
                        resignEnable: values.resignEnable,
                        resignWorkHours: values.resignWorkList.map((item, index) => ({
                            ...resignData.monthList[index],
                            ...item
                        })),
                        workRule: values.commonWorkRule,
                        workYear: values.commonWorkYear
                    };
                    if (!commonDataIsEmpty) {
                        params.commonWorkHours = {
                            ...(values.commonWorkList.length ? values.commonWorkList[0] : {}),
                            workRule: values.commonWorkRule,
                            workYear: values.commonWorkYear
                        };
                    }
                    const { code, msg } = await onSaveWorkingTimeSetting(params);
                    if (code === 10000) {
                        message.success('保存成功！');
                    } else {
                        message.error(msg);
                    }
                    console.log('Received values of form: ', values, selectOrganizationCode);
                    setPageLoading(false);
                } else {
                    message.error('表单有未填项，请填写完整！');
                }
            });
        } catch (e) {
            setPageLoading(false);
        }
    };

    // 基础信息
    const getInfo = async (selectOrg, year, changeType) => {
        try {
            setPageLoading(true);
            const result = await queryWorkingInfo(selectOrg, year);
            console.log('标准工时信息', result);
            const { code, data = {} } = result;
            if (code === 10000) {
                setGeneralData({
                    commonWorkYear: data.workYear,
                    commonWorkRule: data.workRule
                });
                const commonWorkHours = data.commonWorkHours || {};
                setCommonData(
                    isEmpty(commonWorkHours)
                        ? {}
                        : {
                              commonEnable: data.commonEnable,
                              monthList: [commonWorkHours]
                          }
                );
                setResignData({
                    resignEnable: data.resignEnable,
                    monthList: (data.resignWorkHours || []).map((item, index) => ({
                        ...item,
                        name: MONTHList[index].monthName
                    }))
                });

                const { commonWorkRule } = getFieldsValue();
                if (changeType && commonWorkRule !== data.workRule) {
                    setTimeout(() => {
                        setFieldsValue({
                            commonWorkRule: data.workRule
                        });
                    }, 0);
                }
            }
            setPageLoading(false);
        } catch (e) {
            console.log(e);
            setPageLoading(false);
        }
    };

    // 工作制下拉
    const getWeekRule = async () => {
        try {
            const { code, data = {} } = await queryDictList('WorkRuleOptions');
            if (code === 10000) {
                console.log('工作制列表', data);
                setWorkRuleList(data.WorkRuleOptions || []);
            }
        } catch (e) {
            console.log(e);
        }
    };

    // 工作制切换获取当月入离职人员工作日设置信息
    const getWeekCalculate = async val => {
        resetFields();
        const { commonWorkYear } = getFieldsValue();
        setCommonData(
            isEmpty(commonData)
                ? {}
                : {
                      ...commonData,
                      monthList: (commonData?.monthList || []).map(item => ({
                          ...item,
                          workRule: (item.isEdit && val) || item.workRule
                      }))
                  }
        );
        setPageLoading(true);
        try {
            const { code, data = {}, msg } = await queryWorkingCalculate(commonWorkYear, val);
            if (code === 10000) {
                const { monthList, commonEnable, resignEnable } = resignData;

                setResignData({
                    resignEnable,
                    commonEnable,
                    monthList: (monthList || []).map(item => ({
                        ...item,
                        workDays: (item.isEdit && data[item.workMonth]) || item.workDays,
                        workRule: (item.isEdit && val) || item.workRule
                    }))
                });
            } else {
                message.error(msg);
            }
            setPageLoading(false);
        } catch (e) {
            setPageLoading(false);
            console.log(e);
        }
    };

    // 年度下拉
    const getYearList = async companyCode => {
        resetFields();
        try {
            const { code, data = [] } = await querySalaryYearList(companyCode);
            if (code === 10000) {
                setYearList(
                    data.map(y => ({
                        key: y,
                        value: y
                    }))
                );
                if (data.length) {
                    getInfo(companyCode, data[0]);
                }
            }
        } catch (e) {
            console.log(e);
        }
    };

    // 个税基础
    const getBaseSettingInfo = async companyCode => {
        try {
            const { code, data = {} } = await queryBaseSettingInfo(companyCode);
            if (code === 10000) {
                setBaseSettingInfo(data);
            }
        } catch (e) {
            console.log(e);
        }
    };

    useEffect(() => {
        getWeekRule();
    }, []);

    useEffect(() => {
        fetchOrganizationListAndDefault().then(
            ({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);
            }
        );
    }, []);

    useEffect(() => {
        if (selectOrganizationCode) {
            mergeTabStore({
                selectOrganizationCode,
                countryNameCode: null
            });
            getYearList(selectOrganizationCode);
            getBaseSettingInfo(selectOrganizationCode);
        }
    }, [selectOrganizationCode]);

    return (
        <PageHeaderWrapper type="success">
            <TabContextMenuFilter>
                <TabMenuRouter
                    authCodeMap={MENU_AUTH_CODE_MAP}
                    type="workingSetting"
                    extraButton={
                        <div className={salaryStyle.flex}>
                            <div className={classNames([salaryStyle.flex, salaryStyle.mr12])}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    treeDataFromProp
                                    treeDataList={organizationTreeData}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                    value={selectOrganizationCode}
                                    onChange={orgCode => setSelectOrganizationCode(orgCode)}
                                />
                            </div>
                            <div>
                                <Button
                                    onClick={() =>
                                        history.push({
                                            pathname: '/finance/setting/salarySetting/workingSettingLog',
                                            query: {
                                                organizationCode: selectOrganizationCode
                                            },
                                            state: {
                                                tabRoute: true,
                                                tabRefresh: true
                                            }
                                        })
                                    }
                                >
                                    操作日志
                                </Button>
                            </div>
                        </div>
                    }
                >
                    <div className={styles.container} style={{ marginTop: 50 }}>
                        <Spin spinning={pageLoading}>
                            <Form {...formItemLayout} hideRequiredMark>
                                <Row gutter={24}>
                                    <Col span={15}>
                                        <div className={styles.workTimeFormWrap}>
                                            <Col span={8}>
                                                <Form.Item label="年度">
                                                    {getFieldDecorator('commonWorkYear', {
                                                        initialValue: generalData.commonWorkYear,
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '请选择年度'
                                                            }
                                                        ]
                                                    })(
                                                        <CustomerSelect
                                                            dataList={yearList}
                                                            style={{
                                                                width: '65%',
                                                                minWidth: 100
                                                            }}
                                                            onChange={val => getInfo(selectOrganizationCode, val, true)}
                                                        />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="工作制">
                                                    <div className={styles.workTimeItemWrap}>
                                                        {getFieldDecorator('commonWorkRule', {
                                                            initialValue: generalData.commonWorkRule,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请选择工作制'
                                                                }
                                                            ]
                                                        })(
                                                            <CustomerSelect
                                                                dataList={workRuleList}
                                                                style={{
                                                                    width: '65%',
                                                                    minWidth: 100
                                                                }}
                                                                onChange={getWeekCalculate}
                                                            />
                                                        )}
                                                        <span className={styles.workTimeItemUnit}>每周</span>
                                                    </div>
                                                </Form.Item>
                                            </Col>
                                        </div>
                                    </Col>
                                    <Col span={9} style={{ marginLeft: '-18.5%' }}>
                                        <Form.Item {...workTimeInfoLayout}>
                                            <div className={styles.workTimeFormWrap}>
                                                <div className={styles.workTimeInfoContent}>
                                                    <span className={styles.workLabelText}>月薪：</span>
                                                    <NumberSettingInput
                                                        min={0}
                                                        style={{
                                                            maxWidth: '134px',
                                                            width: 'auto'
                                                        }}
                                                        value={currentMoney}
                                                        onChange={setCurrentMoney}
                                                        thousandsSeparator=","
                                                        nonNegative
                                                        maxLength={15}
                                                    />
                                                    <span className={styles.workTimeInfoUnitMargin}>元</span>
                                                    <span className={styles.workTimeInfoTextGray}>
                                                        （输入月薪可自动计算）
                                                    </span>
                                                </div>
                                            </div>
                                        </Form.Item>
                                    </Col>
                                </Row>
                                {commonDataIsEmpty ? null : (
                                    <CommonWorkSetting
                                        form={form}
                                        editData={commonData}
                                        workRuleList={workRuleList}
                                        yearList={yearList}
                                        baseSettingInfo={baseSettingInfo}
                                        currentMoney={currentMoney}
                                        disabled={false}
                                        paramKeys={{
                                            columnName: '正常通用工作日设置',
                                            enableKey: 'commonEnable',
                                            workYearKey: 'commonWorkYear',
                                            workRuleKey: 'commonWorkRule',
                                            workListWrapKey: 'commonWorkList'
                                        }}
                                    />
                                )}
                                <CommonWorkSetting
                                    form={form}
                                    required={commonDataIsEmpty}
                                    editData={resignData}
                                    workRuleList={workRuleList}
                                    yearList={yearList}
                                    baseSettingInfo={baseSettingInfo}
                                    currentMoney={currentMoney}
                                    disabled
                                    paramKeys={{
                                        columnName: commonDataIsEmpty
                                            ? '正常通用工作日设置'
                                            : '当月入离职人员工作日设置',
                                        enableKey: 'resignEnable',
                                        workYearKey: 'resignWorkYear',
                                        workRuleKey: 'resignWorkRule',
                                        workListWrapKey: 'resignWorkList'
                                    }}
                                />
                            </Form>
                            <AuthComponent code="finance:setting:salary:workhour:save">
                                <BottomAction>
                                    <Button type="primary" onClick={onSave}>
                                        保存
                                    </Button>
                                </BottomAction>
                            </AuthComponent>
                        </Spin>
                    </div>
                </TabMenuRouter>
            </TabContextMenuFilter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(connect(() => ({}))(Form.create({ name: 'WorkingTimeSetting' })(WorkingTimeSetting)));
